<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新建/编辑博客 - Lumina AI 内容管理后台</title>
    <script src="../../frontend/assets/js/tailwindcss.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="../../frontend/assets/css/font-awesome.min.css" rel="stylesheet">
    <!-- 本地 Markdown 编辑器 -->
    <link href="../assets/css/simple-md-editor.css" rel="stylesheet">
    <script src="../assets/js/simple-md-editor.js"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
        .container { width: 100%; max-width: none; margin: 0; }
        .editor { min-height: 520px; }
        .input, .textarea, .select { border-width: 2px; }
        .input:focus, .textarea:focus, .select:focus { outline: none; box-shadow: 0 0 0 3px rgba(255,228,92,.25); border-color: #FFE45C; }
        .tag-input { display: flex; flex-wrap: wrap; gap: 8px; padding: 8px; border: 2px solid #e5e7eb; border-radius: 12px; min-height: 44px; }
        .tag { background: #FFE45C; color: #000; padding: 4px 12px; border-radius: 20px; display: flex; align-items: center; gap: 8px; }
        .tag-remove { cursor: pointer; color: #666; }
        .file-upload { border: 2px dashed #d1d5db; border-radius: 12px; padding: 20px; text-align: center; transition: all 0.3s; }
        .file-upload:hover { border-color: #FFE45C; background: #fefce8; }
        .file-upload.dragover { border-color: #FFE45C; background: #fefce8; }
        
        /* 拖拽区域样式 */
        .editor-container { position: relative; }

        #dropZone { 
            position: absolute; 
            top: 0; 
            left: 0; 
            right: 0; 
            bottom: 0; 
            z-index: 10; 
            background: rgba(59, 130, 246, 0.1); 
            border: 2px dashed #3b82f6; 
            border-radius: 8px; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            transition: all 0.3s ease;
            pointer-events: none;
        }
        #dropZone:not(.hidden) { 
            background: rgba(59, 130, 246, 0.15); 
            border-color: #2563eb;
            pointer-events: auto;
        }
        
        /* 响应式优化 */
        @media (max-width: 1024px) {
            .lg\:grid-cols-12 {
                grid-template-columns: 1fr;
            }
            .lg\:col-span-7, .lg\:col-span-5 {
                grid-column: span 1;
            }
        }
        
        /* 移动端优化 */
        @media (max-width: 768px) {
            .container { padding: 1rem; }
            .pt-20 { padding-top: 5rem; }
            .p-6 { padding: 1rem; }
            .gap-6 { gap: 1rem; }
            .space-y-4 > * + * { margin-top: 1rem; }
            .text-xl { font-size: 1.125rem; }
            .text-lg { font-size: 1rem; }
        }
        
        /* 表单元素优化 */
        .form-group { margin-bottom: 1.5rem; }
        .form-group:last-child { margin-bottom: 0; }
        .form-label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: #374151; }
        .form-input { width: 100%; padding: 0.75rem 1rem; border: 2px solid #e5e7eb; border-radius: 0.75rem; transition: all 0.2s; }
        .form-input:focus { outline: none; box-shadow: 0 0 0 3px rgba(255,228,92,.25); border-color: #FFE45C; }
        .form-textarea { resize: vertical; min-height: 100px; }
        
        /* 卡片样式优化 */
        .card { background: white; border-radius: 1rem; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06); border: 1px solid #f3f4f6; padding: 1.5rem; }
        
        /* 按钮样式优化 */
        .btn { display: inline-flex; align-items: center; justify-content: center; padding: 0.75rem 1.5rem; border-radius: 0.75rem; font-weight: 500; transition: all 0.2s; cursor: pointer; border: none; }
        .btn-primary { background: #FFE45C; color: #000; }
        .btn-primary:hover { background: #fdd835; transform: translateY(-1px); }
        .btn-secondary { background: #f3f4f6; color: #374151; }
        .btn-secondary:hover { background: #e5e7eb; }
        .btn-success { background: #10b981; color: white; }
        .btn-success:hover { background: #059669; }
    </style>
    <script>
        tailwind = window.tailwind || {}; tailwind.config = { theme: { extend: { colors: { primary: '#FFE45C' } } } };
    </script>
</head>
<body class="bg-gray-50">
    <!-- Header -->
    <header class="bg-white/95 backdrop-blur-md border-b border-gray-100 shadow-sm fixed top-0 left-0 right-0 z-40">
        <div class="flex items-center justify-between px-4 md:px-6 py-4">
            <div class="flex items-center">
                <a href="/admin/blog/list.html" class="text-gray-500 hover:text-gray-700 mr-3 md:mr-4">
                    <i class="fas fa-arrow-left text-lg md:text-xl"></i>
                </a>
                <div class="flex items-center">
                    <div class="w-6 h-6 md:w-8 md:h-8 bg-gradient-to-r from-yellow-400 to-yellow-500 rounded-lg flex items-center justify-center mr-2 md:mr-3">
                        <i class="fas fa-brain text-white text-xs md:text-sm"></i>
                    </div>
                    <h1 class="text-lg md:text-xl font-bold text-gray-800">新建/编辑博客</h1>
                </div>
            </div>
            <div class="flex items-center space-x-2 md:space-x-3"></div>
        </div>
    </header>

    <main class="pt-16 md:pt-20 p-4 md:p-6 container">
        <div class="grid grid-cols-1 xl:grid-cols-12 gap-4 md:gap-6">
            <!-- 左侧：Markdown编辑器 -->
            <section class="xl:col-span-7 order-2 xl:order-1">
                <div class="card">
                    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-4 gap-3">
                        <label class="form-label text-base md:text-lg">内容（Markdown）</label>
                        <div class="flex space-x-2">
                            <button id="uploadMdBtn" class="btn btn-primary text-sm">
                                <i class="fas fa-upload mr-2"></i>上传MD文件
                            </button>
                            <input type="file" id="mdFileInput" accept=".md,.markdown,.txt" class="hidden" />
                        </div>
                    </div>
                    <div class="editor-container">
                        <div id="mdEditor" class="editor w-full" 
                             ondrop="handleDrop(event)" 
                             ondragover="handleDragOver(event)" 
                             ondragleave="handleDragLeave(event)">
                        </div>
                        <div id="dropZone" class="hidden">
                            <div class="text-center">
                                <i class="fas fa-cloud-upload-alt text-3xl md:text-4xl text-blue-400 mb-2"></i>
                                <p class="text-blue-600 font-medium text-sm md:text-base">释放文件以上传</p>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- 右侧：元数据与操作按钮 -->
            <aside class="xl:col-span-5 order-1 xl:order-2 space-y-4 md:space-y-6">
                <!-- 基本信息 -->
                <div class="card">
                    <h3 class="text-lg font-medium text-gray-800 mb-4">基本信息</h3>
                    
                    <div class="form-group">
                        <label class="form-label">标题 <span class="text-red-500">*</span></label>
                        <input id="title" class="form-input" placeholder="请输入博客标题" />
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">摘要 <span class="text-red-500">*</span></label>
                        <textarea id="summary" class="form-input form-textarea" rows="3" placeholder="简要描述这篇博客的内容和亮点"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">分类 <span class="text-red-500">*</span></label>
                        <select id="category" class="form-input">
                            <option value="">请选择分类</option>
                            <option value="职业发展">职业发展</option>
                            <option value="技术实践">技术实践</option>
                            <option value="硬件分析">硬件分析</option>
                            <option value="安全伦理">安全伦理</option>
                            <option value="行业趋势">行业趋势</option>
                            <option value="学习资源">学习资源</option>
                            <option value="项目实战">项目实战</option>
                            <option value="产品创新">产品创新</option>
                            <option value="产品思考">产品思考</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">标签</label>
                        <div id="tagInput" class="tag-input">
                            <input type="text" id="tagInputField" placeholder="输入标签后按回车添加" class="flex-1 border-none outline-none bg-transparent" />
                        </div>
                        <div id="tagsContainer" class="mt-2 flex flex-wrap gap-2"></div>
                    </div>
                </div>

                <!-- 作者信息 -->
                <div class="card">
                    <h3 class="text-lg font-medium text-gray-800 mb-4">作者信息</h3>
                    
                    <div class="form-group">
                        <label class="form-label">作者姓名 <span class="text-red-500">*</span></label>
                        <input id="author" class="form-input" placeholder="作者名称" />
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">作者职称</label>
                        <input id="authorTitle" class="form-input" placeholder="如：AI产品专家、技术架构师等" />
                    </div>
                </div>

                <!-- 发布设置 -->
                <div class="card">
                    <h3 class="text-lg font-medium text-gray-800 mb-4">发布设置</h3>
                    
                    <div class="form-group">
                        <label class="form-label">发布日期</label>
                        <input type="date" id="publishDate" class="form-input" />
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">状态</label>
                        <select id="status" class="form-input">
                            <option value="draft">草稿</option>
                            <option value="published">已发布</option>
                        </select>
                    </div>
                    
                    <div class="flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4">
                        <label class="flex items-center">
                            <input type="checkbox" id="isHot" class="mr-2 rounded text-yellow-500 focus:ring-yellow-500" />
                            <span class="text-sm text-gray-700">热门文章</span>
                        </label>
                        <label class="flex items-center">
                            <input type="checkbox" id="isFeatured" class="mr-2 rounded text-yellow-500 focus:ring-yellow-500" />
                            <span class="text-sm text-gray-700">推荐文章</span>
                        </label>
                    </div>
                </div>

                <!-- 封面设置 -->
                <div class="card">
                    <h3 class="text-lg font-medium text-gray-800 mb-4">封面设置</h3>
                    
                    <div class="form-group">
                        <label class="form-label">封面图片</label>
                        <div class="flex flex-col sm:flex-row items-start sm:items-center gap-3 sm:gap-4">
                            <div class="w-20 h-16 sm:w-24 sm:h-16 bg-gray-100 rounded-lg flex items-center justify-center overflow-hidden border border-gray-200 flex-shrink-0">
                                <img id="coverPreview" src="" alt="预览" class="w-full h-full object-cover hidden" />
                                <span id="coverPlaceholder" class="text-gray-400 text-xs sm:text-sm">无预览</span>
                            </div>
                            <div class="flex-1 flex flex-col sm:flex-row items-start sm:items-center gap-2 w-full">
                                <input id="coverImage" class="form-input flex-1" placeholder="图片文件名，如：ai-hardware.jpg" />
                                <input type="file" id="coverFile" accept="image/*" class="hidden" />
                                <button id="coverUploadBtn" class="btn btn-secondary text-sm whitespace-nowrap">上传图片</button>
                            </div>
                        </div>
                        <p class="text-xs text-gray-500 mt-2">支持 jpg/png/webp，选择图片会自动填充文件名到输入框。</p>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">图标</label>
                        <select id="icon" class="form-input">
                            <option value="fas fa-lightbulb">💡 灯泡</option>
                            <option value="fas fa-terminal">💻 终端</option>
                            <option value="fas fa-microchip">🔧 芯片</option>
                            <option value="fas fa-shield-alt">🛡️ 盾牌</option>
                            <option value="fas fa-chart-line">📈 图表</option>
                            <option value="fas fa-graduation-cap">🎓 毕业帽</option>
                            <option value="fas fa-rocket">🚀 火箭</option>
                            <option value="fas fa-brain">🧠 大脑</option>
                            <option value="fas fa-user-graduate">👨‍🎓 毕业生</option>
                            <option value="fas fa-user-tie">👔 商务人士</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">图标颜色</label>
                        <select id="iconColor" class="form-input">
                            <option value="yellow">黄色</option>
                            <option value="blue">蓝色</option>
                            <option value="green">绿色</option>
                            <option value="purple">紫色</option>
                            <option value="pink">粉色</option>
                            <option value="indigo">靛蓝</option>
                            <option value="orange">橙色</option>
                            <option value="red">红色</option>
                            <option value="teal">青色</option>
                        </select>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div class="card">
                    <div class="flex flex-col space-y-3">
                        <button id="saveDraft" class="btn btn-secondary">
                            <i class="fas fa-save mr-2"></i>保存草稿
                        </button>
                        <button id="publish" class="btn btn-success">
                            <i class="fas fa-paper-plane mr-2"></i>保存并发布
                        </button>
                        <button id="preview" class="btn btn-primary">
                            <i class="fas fa-eye mr-2"></i>预览效果
                        </button>
                    </div>
                </div>
            </aside>
        </div>
    </main>

    <!-- CSRF Token -->
    <input type="hidden" name="csrfmiddlewaretoken" value="">
    
    <script src="../js/auth.js"></script>
    <script src="../js/common.js"></script>
    <script>
        // 获取CSRF Token
        async function getCsrfToken() {
            try {
                const response = await fetch('http://localhost:8001/api/auth/csrf-token/');
                if (response.ok) {
                    const data = await response.json();
                    document.querySelector('[name=csrfmiddlewaretoken]').value = data.csrfToken;
                }
            } catch (error) {
                console.error('获取CSRF Token失败:', error);
            }
        }

        // 初始化 Markdown 编辑器
        let easyMDE;
        let currentTags = [];
        let blogsData = { blogs: [], categories: [], authors: [], tags: [] };
        
        // 读取 URL 参数
        function getParam(key){ const u=new URL(location.href); return u.searchParams.get(key); }
        
        // 标签管理
        function addTag(tagText) {
            const tag = tagText.trim();
            if (tag && !currentTags.includes(tag)) {
                currentTags.push(tag);
                renderTags();
            }
        }
        
        function removeTag(tagText) {
            currentTags = currentTags.filter(tag => tag !== tagText);
            renderTags();
        }
        
        function renderTags() {
            const container = document.getElementById('tagsContainer');
            container.innerHTML = currentTags.map(tag => `
                <span class="tag">
                    ${tag}
                    <span class="tag-remove" onclick="removeTag('${tag}')">&times;</span>
                </span>
            `).join('');
        }
        
        // 拖拽上传处理
        function handleDrop(event) {
            event.preventDefault();
            event.stopPropagation();
            
            const dropZone = document.getElementById('dropZone');
            if (dropZone) dropZone.classList.add('hidden');
            
            const files = event.dataTransfer.files;
            if (files.length > 0) {
                handleFileUpload(files[0]);
            }
        }
        
        function handleDragOver(event) {
            event.preventDefault();
            event.stopPropagation();
            
            const dropZone = document.getElementById('dropZone');
            if (dropZone) dropZone.classList.remove('hidden');
        }
        
        function handleDragLeave(event) {
            event.preventDefault();
            event.stopPropagation();
            
            const dropZone = document.getElementById('dropZone');
            if (dropZone) dropZone.classList.add('hidden');
        }
        
        // 文件处理函数
        function handleFileUpload(file) {
            console.log('处理文件上传:', file.name, file.type, file.size);
            
            // 检查文件类型
            const isValidFile = file.name.endsWith('.md') || 
                              file.name.endsWith('.markdown') || 
                              file.type === 'text/markdown' ||
                              file.type === 'text/plain';
            
            if (!isValidFile) {
                console.error('无效的文件类型:', file.type);
                if (typeof commonManager !== 'undefined' && commonManager.showError) {
                    commonManager.showError('请选择有效的MD文件（.md或.markdown格式）');
                } else {
                    alert('请选择有效的MD文件（.md或.markdown格式）');
                }
                return;
            }
            
            // 读取文件内容
            const reader = new FileReader();
            
            reader.onload = (e) => {
                const content = e.target.result;
                console.log('文件内容读取成功，长度:', content.length);
                
                // 将内容设置到编辑器
                if (easyMDE && typeof easyMDE.value === 'function') {
                    easyMDE.value(content);
                    console.log('内容已设置到EasyMDE编辑器');
                } else {
                    const contentTextarea = document.getElementById('content');
                    if (contentTextarea) {
                        contentTextarea.value = content;
                        console.log('内容已设置到备用textarea');
                    } else {
                        console.error('找不到内容编辑器');
                    }
                }
                
                // 显示成功消息
                if (typeof commonManager !== 'undefined' && commonManager.showSuccess) {
                    commonManager.showSuccess('MD文件上传成功！');
                } else {
                    alert('MD文件上传成功！');
                }
            };
            
            reader.onerror = (e) => {
                console.error('文件读取失败:', e);
                if (typeof commonManager !== 'undefined' && commonManager.showError) {
                    commonManager.showError('文件读取失败，请重试');
                } else {
                    alert('文件读取失败，请重试');
                }
            };
            
            // 开始读取文件
            reader.readAsText(file, 'UTF-8');
        }
        
        // MD文件上传处理
        function setupFileUpload() {
            const uploadBtn = document.getElementById('uploadMdBtn');
            const fileInput = document.getElementById('mdFileInput');
            
            if (!uploadBtn || !fileInput) {
                console.error('文件上传元素未找到');
                return;
            }
            
            console.log('设置文件上传功能...');
            
            // 点击上传按钮时触发文件选择
            uploadBtn.addEventListener('click', (e) => {
                e.preventDefault();
                console.log('点击上传按钮');
                fileInput.click();
            });
            
            // 文件选择变化时的处理
            fileInput.addEventListener('change', (e) => {
                console.log('文件选择变化:', e.target.files);
                const file = e.target.files[0];
                
                if (!file) {
                    console.log('没有选择文件');
                    return;
                }
                
                // 使用统一的文件处理函数
                handleFileUpload(file);
                
                // 清空文件输入，允许重复选择同一文件
                fileInput.value = '';
            });
            
            console.log('文件上传功能设置完成');
        }

        // 封面图片上传与预览
        function setupCoverUpload() {
            const btn = document.getElementById('coverUploadBtn');
            const fileInput = document.getElementById('coverFile');
            const input = document.getElementById('coverImage');
            const preview = document.getElementById('coverPreview');
            const placeholder = document.getElementById('coverPlaceholder');

            if (!btn || !fileInput || !input || !preview || !placeholder) return;

            btn.addEventListener('click', (e) => {
                e.preventDefault();
                fileInput.click();
            });

            fileInput.addEventListener('change', (e) => {
                const file = e.target.files && e.target.files[0];
                if (!file) return;

                if (!file.type.startsWith('image/')) {
                    if (typeof commonManager !== 'undefined' && commonManager.showError) {
                        commonManager.showError('请选择图片文件');
                    }
                    return;
                }

                // 预览
                const url = URL.createObjectURL(file);
                preview.src = url;
                preview.classList.remove('hidden');
                placeholder.classList.add('hidden');

                // 填充文件名（保持与Blogs.json一致的文件名风格）
                input.value = file.name;
            });
        }
        
        // 加载博客数据
        async function loadBlogsData() {
            try {
                const response = await fetch('../../frontend/AiBlog/Blogs.json');
                if (response.ok) {
                    blogsData = await response.json();
                    console.log('博客数据加载成功:', blogsData);
                } else {
                    console.error('加载博客数据失败:', response.status);
                    blogsData = { blogs: [], categories: [], authors: [], tags: [] };
                }
            } catch (error) {
                console.error('加载博客数据失败:', error);
                blogsData = { blogs: [], categories: [], authors: [], tags: [] };
            }
        }
        
        // 根据ID填充表单
        function fillFormById(id) {
            const blog = blogsData.blogs.find(b => String(b.id) === String(id));
            if (!blog) return;
            
            // 基本信息
            document.getElementById('title').value = blog.title || '';
            document.getElementById('summary').value = blog.summary || '';
            document.getElementById('category').value = blog.category || '';
            
            // 标签
            currentTags = blog.tags || [];
            renderTags();
            
            // 作者信息
            document.getElementById('author').value = blog.author || '';
            document.getElementById('authorTitle').value = blog.authorTitle || '';
            
            // 发布设置
            document.getElementById('publishDate').value = blog.publishDate || new Date().toISOString().split('T')[0];
            document.getElementById('status').value = blog.status || 'draft';
            document.getElementById('isHot').checked = blog.isHot || false;
            document.getElementById('isFeatured').checked = blog.isFeatured || false;
            
            // 封面设置
            document.getElementById('coverImage').value = blog.coverImage || '';
            document.getElementById('icon').value = blog.icon || 'fas fa-lightbulb';
            document.getElementById('iconColor').value = blog.iconColor || 'yellow';

            // 预览封面
            const preview = document.getElementById('coverPreview');
            const placeholder = document.getElementById('coverPlaceholder');
            if (blog.coverImage) {
                preview.src = `../../frontend/assets/img/${blog.coverImage}`;
                preview.classList.remove('hidden');
                placeholder.classList.add('hidden');
            } else {
                preview.src = '';
                preview.classList.add('hidden');
                placeholder.classList.remove('hidden');
            }
            
            // 内容 - 需要从contentFile读取
            if (blog.contentFile) {
                loadContentFromFile(blog.contentFile);
            }
        }
        
        // 从文件加载内容
        async function loadContentFromFile(contentFile) {
            try {
                const response = await fetch(`../../frontend/AiBlog/${contentFile}`);
                if (response.ok) {
                    const content = await response.text();
                    if (easyMDE) {
                        easyMDE.value(content);
                    } else {
                        const contentTextarea = document.getElementById('content');
                        if (contentTextarea) contentTextarea.value = content;
                    }
                }
            } catch (error) {
                console.error('加载内容文件失败:', error);
            }
        }
        
        // 生成新的博客ID
        function generateNewId() {
            if (blogsData.blogs.length === 0) return 1;
            const maxId = Math.max(...blogsData.blogs.map(b => b.id));
            return maxId + 1;
        }
        
        // 生成内容文件名
        function generateContentFileName(title) {
            const cleanTitle = title.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '');
            return `Blogs/${cleanTitle}.md`;
        }
        
        // 创建或更新Markdown内容文件
        async function createContentFile(fileName, content) {
            try {
                // 使用后端API创建文件
                const response = await fetch('http://localhost:8001/api/blogs/create-content-file/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        fileName: fileName,
                        content: content
                    })
                });
                
                if (response.ok) {
                    console.log('内容文件创建成功:', fileName);
                    return true;
                } else {
                    throw new Error('创建内容文件失败');
                }
            } catch (error) {
                console.error('创建内容文件失败:', error);
                return false;
            }
        }
        
        // 保存博客到本地JSON文件
        async function saveBlogToJson(blogData, isPublish) {
            try {
                const id = getParam('id');
                let blog;
                
                if (id) {
                    // 更新现有博客
                    const index = blogsData.blogs.findIndex(b => String(b.id) === String(id));
                    if (index !== -1) {
                        blog = { ...blogsData.blogs[index], ...blogData };
                        blogsData.blogs[index] = blog;
                    }
                } else {
                    // 创建新博客
                    blog = {
                        id: generateNewId(),
                        ...blogData,
                        readCount: 0,
                        likeCount: 0,
                        commentCount: 0
                    };
                    blogsData.blogs.push(blog);
                }
                
                // 更新统计信息
                updateStatistics();
                
                // 保存到后端API
                const saveResponse = await fetch('http://localhost:8001/api/blogs/save-json/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(blogsData)
                });
                
                if (saveResponse.ok) {
                    console.log('博客数据已保存到JSON文件:', blog);
                    
                    // 显示成功消息
                    if (typeof commonManager !== 'undefined' && commonManager.showSuccess) {
                        commonManager.showSuccess(`博客${id ? '更新' : '创建'}成功！`);
                    } else {
                        alert(`博客${id ? '更新' : '创建'}成功！`);
                    }
                    
                    // 如果是新创建的博客，跳转到编辑页面
                    if (!id) {
                        window.location.href = `edit.html?id=${blog.id}`;
                    }
                } else {
                    throw new Error('保存JSON文件失败');
                }
                
            } catch (error) {
                console.error('保存博客失败:', error);
                if (typeof commonManager !== 'undefined' && commonManager.showError) {
                    commonManager.showError(`保存失败: ${error.message}`);
                } else {
                    alert(`保存失败: ${error.message}`);
                }
            }
        }
        
        // 更新统计信息
        function updateStatistics() {
            // 更新分类统计
            blogsData.categories.forEach(cat => {
                cat.count = blogsData.blogs.filter(b => b.category === cat.name).length;
            });
            
            // 更新作者统计
            blogsData.authors.forEach(author => {
                author.articleCount = blogsData.blogs.filter(b => b.author === author.name).length;
            });
            
            // 更新标签列表
            const allTags = new Set();
            blogsData.blogs.forEach(blog => {
                if (blog.tags) {
                    blog.tags.forEach(tag => allTags.add(tag));
                }
            });
            blogsData.tags = Array.from(allTags);
        }
        
        async function init() {
            try {
                // 检查本地编辑器是否加载成功
                if (typeof SimpleMDEditor === 'undefined') {
                    console.error('本地编辑器未加载，使用备用方案');
                    // 备用方案：使用普通 textarea
                    const mdEditor = document.getElementById('mdEditor');
                    mdEditor.innerHTML = `
                        <textarea id="content" class="form-input form-textarea" 
                            placeholder="在此输入 Markdown 内容..." rows="20"></textarea>
                    `;
                } else {
                    // 初始化本地 Markdown 编辑器
                    easyMDE = new SimpleMDEditor(document.getElementById('mdEditor'), {
                        placeholder: '在此输入 Markdown 内容...',
                        value: ''
                    });
                    console.log('本地 Markdown 编辑器初始化成功');
                }
                
                // 设置文件上传
                setupFileUpload();
                // 封面上传与预览
                setupCoverUpload();
                
                // 设置标签输入
                const tagInputField = document.getElementById('tagInputField');
                tagInputField.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        addTag(tagInputField.value);
                        tagInputField.value = '';
                    }
                });
                
                // 设置默认发布日期
                document.getElementById('publishDate').value = new Date().toISOString().split('T')[0];
                
            } catch (error) {
                console.error('初始化失败:', error);
            }
            
            await loadBlogsData();
            const id = getParam('id');
            if (id) fillFormById(id);
        }
        
        // 保存博客
        async function upsertBlog(isPublish) {
            try {
                // 验证必填字段
                const title = document.getElementById('title').value.trim();
                const summary = document.getElementById('summary').value.trim();
                const category = document.getElementById('category').value;
                const author = document.getElementById('author').value.trim();
                
                if (!title) {
                    commonManager.showError('请输入博客标题');
                    return;
                }
                if (!summary) {
                    commonManager.showError('请输入博客摘要');
                    return;
                }
                if (!category) {
                    commonManager.showError('请选择博客分类');
                    return;
                }
                if (!author) {
                    commonManager.showError('请输入作者姓名');
                    return;
                }
                
                // 获取内容
                let content = '';
                if (easyMDE) {
                    content = easyMDE.value();
                } else {
                    const contentTextarea = document.getElementById('content');
                    if (contentTextarea) content = contentTextarea.value;
                }
                
                if (!content.trim()) {
                    commonManager.showError('请输入博客内容');
                    return;
                }
                
                // 生成内容文件名
                const contentFileName = generateContentFileName(title);
                
                // 创建内容文件
                const contentFileCreated = await createContentFile(contentFileName, content);
                if (!contentFileCreated) {
                    commonManager.showError('创建内容文件失败');
                    return;
                }
                
                const blogData = {
                    title: title,
                    summary: summary,
                    contentFile: contentFileName,
                    category: category,
                    tags: currentTags,
                    author: author,
                    authorTitle: document.getElementById('authorTitle').value.trim(),
                    publishDate: document.getElementById('publishDate').value,
                    status: isPublish ? 'published' : 'draft',
                    isHot: document.getElementById('isHot').checked,
                    isFeatured: document.getElementById('isFeatured').checked,
                    coverImage: document.getElementById('coverImage').value.trim(),
                    icon: document.getElementById('icon').value,
                    iconColor: document.getElementById('iconColor').value
                };
                
                // 保存到本地JSON
                await saveBlogToJson(blogData, isPublish);
                
            } catch (error) {
                console.error('保存博客失败:', error);
                if (typeof commonManager !== 'undefined' && commonManager.showError) {
                    commonManager.showError(`保存失败: ${error.message}`);
                } else {
                    alert(`保存失败: ${error.message}`);
                }
            }
        }
        
        // 预览功能
        function previewBlog() {
            const content = easyMDE ? easyMDE.value() : document.getElementById('content')?.value || '';
            if (!content.trim()) {
                commonManager.showError('请先输入博客内容');
                return;
            }
            
            const title = document.getElementById('title').value || '新建博客';
            
            // 创建预览窗口
            const previewWindow = window.open('', '_blank');
            const previewHtml = `
                <!DOCTYPE html>
                <html>
                <head>
                    <title>博客预览 - ${title}</title>
                    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
                    <style>
                        body { font-family: 'Inter', sans-serif; margin: 0 auto; padding: 20px; line-height: 1.6; }
                        h1, h2, h3 { color: #1f2937; }
                        code { background: #f3f4f6; padding: 2px 6px; border-radius: 4px; }
                        pre { background: #f3f4f6; padding: 16px; border-radius: 8px; overflow-x: auto; }
                        blockquote { border-left: 4px solid #FFE45C; padding-left: 16px; margin-left: 0; color: #6b7280; }
                    </style>
                </head>
                <body>
                    <h1>${title}</h1>
                    <div id="content"></div>
                    <script>
                        document.getElementById('content').innerHTML = marked.parse(\`${content}\`);
                    </script>
                </body>
                </html>
            `;
            previewWindow.document.write(previewHtml);
        }
        
        // 绑定事件
        document.getElementById('saveDraft').onclick = () => upsertBlog(false);
        document.getElementById('publish').onclick = () => upsertBlog(true);
        document.getElementById('preview').onclick = previewBlog;
        
        // 初始化时获取CSRF Token
        getCsrfToken();
        init();
    </script>
</body>
</html>
